<template>
  <div class="content">
    <!-- 顶部搜索栏 -->
    <div class="top">
      <a-card :bordered="false">
        <a-space :size="20">
          <a-button type="primary" @click="showModal" ghost
            ><PlusCircleOutlined />新增</a-button
          >
          <a-popconfirm
            title="确认删除？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="removeBachById"
            @cancel="cancel"
          >
            <a-button :disabled="!hasSelected" type="primary" danger ghost
              ><DeleteOutlined />批量删除</a-button
            >
          </a-popconfirm>
        </a-space>
      </a-card>
    </div>

    <!-- 表格数据展示 -->
    <div class="table">
      <a-card :bordered="false">
        <a-collapse
          :ghost="true"
          :accordion="true"
          :bordered="false"
          @change="getStoreGoods"
          v-model:activeKey="activeKey"
        >
          <a-collapse-panel
            :key="item.id"
            :header="item.value"
            v-for="item in stores"
            style="margin-bottom: 65px"
          >
            <!-- 商品表格 -->
            <div v-if="isHaveData">
              <a-table
                :row-selection="{
                  selectedRowKeys: state.selectedRowKeys,
                  onChange: onSelectChange,
                }"
                :data-source="data"
                :pagination="false"
                :scroll="{ x: 1000, y: 1400 }"
                :loading="loading"
              >
                <a-table-column
                  fixed="left"
                  key="image"
                  title="商品图"
                  data-index="image"
                >
                  <template #default="{ record }">
                    <a-image :width="100" :src="record.image" />
                  </template>
                </a-table-column>
                <a-table-column
                  key="name"
                  title="商品名"
                  data-index="name"
                  :ellipsis="true"
                />
                <a-table-column key="brand" title="品牌" data-index="brand" />
                <a-table-column
                  key="category"
                  title="分类"
                  data-index="category"
                />
                <a-table-column key="number" title="数量" data-index="number" />
                <a-table-column key="price" title="单价" data-index="price">
                  <template #default="{ record }">
                    <a-tag color="#f40">
                      <template #icon>
                        <PayCircleOutlined />
                      </template>
                      <span style="font-size: 16px; font-weight: bold">{{
                        towNumber(parseInt(record.price))
                      }}</span>
                    </a-tag>
                  </template>
                </a-table-column>
                <a-table-column key="unit" title="单位" data-index="unit" />
                <a-table-column
                  :ellipsis="true"
                  key="detail"
                  title="详情"
                  data-index="detail"
                >
                  <template #default="{ record }">
                    <a-button type="primary" @click="toOpenModal(record.detail)">查看详情</a-button>
                  </template>
                </a-table-column>
                <a-table-column key="status" title="状态">
                  <template #default="{ record }">
                    <span>
                      <a-tag v-if="record.status === '上架'" color="success">
                        {{ record.status }}</a-tag
                      >
                      <a-tag v-else color="error"> {{ record.status }}</a-tag>
                    </span>
                  </template>
                </a-table-column>
                <a-table-column fixed="right" key="id" title="操作">
                  <template #default="{ record }">
                    <div style="display: flex">
                      <div>
                        <a-button @click="edit(record.key)" type="primary" ghost
                          ><FormOutlined
                        /></a-button>
                      </div>
                      <div style="margin-left: 10px">
                        <a-popconfirm
                          title="确认删除？"
                          ok-text="确认"
                          cancel-text="取消"
                          @confirm="remove(record.key)"
                          @cancel="cancel"
                        >
                          <a-button type="primary" ghost danger>
                            <DeleteOutlined href="#" />
                          </a-button>
                        </a-popconfirm>
                      </div>
                    </div>
                  </template>
                </a-table-column>
              </a-table>

              <!-- 分页 -->
              <div
                class="paginAtion"
                style="
                  height: 40px;
                  width: 100%;
                  margin-top: 10px;
                  display: flex;
                  justify-content: center;
                "
              >
                <a-pagination
                  v-model:current="pageNo"
                  v-model:pageSize="pageSize"
                  show-size-changer
                  :total="total"
                  @change="handlePageChange"
                  :show-total="(total) => `共 ${total} 条`"
                />
              </div>
            </div>

            <!-- 空状态 -->
            <a-empty
              v-if="!isHaveData"
              :image="simpleImage"
              description="暂无任何商品"
            />
          </a-collapse-panel>
        </a-collapse>

        <!-- 空状态 -->
        <div
          v-if="isHaveStore"
          style="
            width: 100%;
            height: 80vh;
            display: flex;
            justify-content: center;
            align-items: center;
          "
        >
          <a-empty>
            <template #description>
              <span style="color: coral"> 暂无任何商品，请先创建店铺! </span>
            </template>
          </a-empty>
        </div>
      </a-card>
    </div>

    <!-- 商品详情弹出框 -->
    <div>
      <a-modal
        v-model:open="open"
        @cancel="handleCancel"
        title="商品详情"
        :footer="null"
      >
        <div>
          <div v-html="detail"></div>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import {
  PlusCircleOutlined,
  DeleteOutlined,
  FormOutlined,
  PayCircleOutlined,
} from "@ant-design/icons-vue";
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  list,
  removeBatchByKeys,
  getBrand,
  getCategory,
  getStores,
} from "@/api/goods";
import { useAdminStore } from "@/stores/admin";
import router from "@/router";
import { Empty } from "ant-design-vue";
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const activeKey = ref(null);
const data = ref([{}]);

const loading = ref(true);
const adminStore = useAdminStore();
const brands = ref([]);
const categorys = ref([]);
const stores = ref([]);
const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(10);
const isAdmin = ref(false);
if (adminStore.admin.role === "管理员") {
  isAdmin.value = true;
}
const isHaveStore = ref(false);
onMounted(() => {
  //获取商品品牌
  getBrand().then((res) => {
    if (res.code === 200) {
      brands.value = res.data;
    }
  });
  //获取商品分类
  getCategory().then((res) => {
    if (res.code === 200) {
      categorys.value = res.data;
    }
  });
  //获取商品店铺
  getStores(adminStore.admin.key).then((res) => {
    if (res.code === 200 && res.data !== null) {
      stores.value = res.data;
    } else {
      isHaveStore.value = true;
    }
  });
});
//请求管理员数据
const isHaveData = ref(true);
function getGoods() {
  list(pageNo.value, pageSize.value, storeId.value).then((res) => {
    if (res.code === 200 && res.data != null) {
      isHaveData.value = true;
      data.value = res.data.data;
      total.value = res.data.total;
    } else {
      isHaveData.value = false;
    }
  });
}

const open = ref(false);
const detail = ref("");
function toOpenModal(e) {
  open.value = true;
  detail.value = e;
}

//监听分页变化
function handlePageChange(param1, param2) {
  pageNo.value = param1;
  pageSize.value = param2;
  getGoods();
}

//获取某店铺的商品数据
const storeId = ref(null);
function getStoreGoods(key) {
  loading.value = true;
  storeId.value = key;
  setTimeout(() => {
    getGoods();
    loading.value = false;
  }, 1500);
}

//新增管理员弹框
const showModal = () => {
  router.push("/addGoods");
};

//管理员修改操作
const isEdit = true;
function edit(id) {
  router.push({ name: "AddGoods", query: { id: id, isEdit: isEdit } });
}

//管理员确认删除回调操作
function remove(id) {
  removeBatchByKeys(id).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getGoods();
    }
  });
}

//管理员取消删除回调操作
function cancel() {
  message.warning("取消删除！");
}

//存储批量管理员id
const state = reactive({
  selectedRowKeys: [],
});
//当有一个或多个管理员被选中时触发按钮
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//批量删除管理员
const removeBachById = () => {
  setTimeout(() => {
    state.selectedRowKeys = [];
  }, 1000);
  //删除后做操作
  removeBatchByKeys(state.selectedRowKeys).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getGoods();
    }
  });
};
//当选中行改变时触发
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};


//展示价格的小数方法
function towNumber(val) {
  return val.toFixed(2);
}
</script>

<style scoped>
.options {
  margin-top: 10px;
}

.table {
  margin-top: 10px;
}

.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

:deep(.ant-card-body) {
  padding: 10px;
}
</style>>